<?php

require_once(dirname(dirname(dirname(dirname(__FILE__)))).'/appconf.php');
  
require_once "CMS.class.php";

$local_config = array(
    'this_cgi'       => 'cms/builder/product/application.php',
    'tmpl'           => array('base_path' => 'cms/builder/product/application/'), # full path = $this->param('TMPL').$
    'database'       => '',
    'table'          => 'product_application',
    'cms_auth_group'  => 'User Data',
    '#MESSAGE#'      => array(),
);

class cms_builder_product_application extends CMS{

  function setup(){
    $this->run_modes('list',
                     'edit',
                     
                     'update', 
                     'mupdate',
                     
                     'add', 
                     'madd', 
                     'showadd', 'edit_after_add',
                     
                     'showdel', 
                     'del', 
                     
                     'showsearch','search','clearsearch',
                     
                     'showsetting', 'setting',
                     
                     'ajax_update_field',
                     
                     'update_score','send_mail','update_accept_period','add_participant','user_accept_invite',
                     'trap'
                    );
    $this->start_mode('list');
    $this->set_path_info_position(array('oid'=>1, 'id'=>2));
    parent::setup();
  }

  function cgiapp_prerun($rm=''){
    
    parent::cgiapp_prerun($rm); # login, targeted to run CMS_Login.class.php 
    
  }

  function cgiapp_postrun(&$body){
    parent::cgiapp_postrun($body);

    $a_js = array();
    if (method_exists($this, 'inject_js') && count($this->inject_js()) > 0){ // some old CMS.class.php don't support yet
    	$a_js = $this->inject_js();
    }
    
	$oid = $this->get_param('pq', 'oid');
	$label = $this->get_parent_label($oid);
	
	if (empty_string($label)){
		$label = ' <span class="pswarning">Unknown &gt; </span>';
	} else {
		$label = $label.' &gt; ';
	}
	array_push($a_js, "$('#parent_key_label').html('$label');");

  //	
    
    $login = $this->get_cms_username();
    if (!empty_string($login)){
      array_push($a_js, "\$('#login').html('Hi $login!  <a href=\"/cms/builder/logout.php\" style=\"color:red;\">Logout</a>');");
    }
  
    if ($this->header_type() == 'redirect'){
      return;	
    }
    
    $a_msg = array();
    $a_current_msg = $this->message();
    $a_session_msg = $this->get_message_from_session();
    foreach ($a_session_msg as $msg){
    	array_push($a_msg, $msg);
    }
    foreach ($a_current_msg as $msg){
    	array_push($a_msg, $msg);
    }
    
    $message = '';
    if (count($a_msg)>0){
      $message = implode('<BR>', $a_msg);
      array_push($a_js, "\$(document).ready(function(){ $(\"#dialog-modal\").dialog({height: 140,modal: true});  });");
    }

    if (count($a_js) > 0){
      $temp = "<script>".implode('', $a_js)."</script>";
      if ($message != ''){
        $temp .= html_dialog('Notice', $message);
      }
      $body = preg_replace('/(<!--POSTRUNJS-->)/', $temp, $body, 1);
      
    }
    
  }
// $oid - id of parent
// 
function get_parent_label($oid){

  $dbh_r = $this->db_connect('read');
  $parent_table = 'product';
  $cname = db_select_one($dbh_r, 'select cname from '.$parent_table.' where id='.$oid);

  return '<a href="/cms/builder/product.php">產品</a> - '.$cname;
}
#no no login

  // some
  function trap(){
	  $a_msg = $this->message();
	  $message = '';
	  if (count($a_msg)>0){
	    $message = implode('<BR>', $a_msg);
	    $this->tmpl_assign('title', 'Application Error');
	    $this->tmpl_assign('body',  $message);
  	  return $this->load_tmpl($this->param('TMPL'),  'error.html');
    }
    return '';
  }

  function action_list(){
  	if (! $this->user_can('list') ) return $this->trap();
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    # on_start_list() *removed* - give it a chance to modify FK and TOP

    $dbh_r = $this->db_connect('read');
    $list_control = $this->update_listing_ordering();
    $sqlstr = 'SELECT * FROM '.$this->param('table').
              $this->listing_condition();
    if ($this->get_q('page', false, 'int')===false) $this->q_param('page', $this->s_param('cms_builder_product_application#'.'page'));

    $application_status = $this->create_lookup_array($dbh_r, "application_status", 'id', "cname", 'where status=1'); 
    $h_feature = array(
      'application_status' => array('h:label',         'application_status', $application_status ,array()),
      'is_fb_share'      => array('ny:label',        'is_fb_share',     ),
      'email_sent'       => array('ny:label',        'email_sent',      ),
      'is_approved'      => array('ny:radio',        'is_approved',     ),
      '#ROW_FUNCTION#' => 'list_row_function',
      
      '#MULTIPLE#' =>1,
      '#PAGESIZE#' => 20,
      '#PAGELIST#' => '1,2,3',
      '#PAGE#'     => $this->get_param('q', 'page', 1, 'int'),
      '#GET_SELECTED_ID#' => 1,
      '#EXTRAQUERYSTR#' => "&oid=$oid"
      );
    list($list_data, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);

    $this->s_param('cms_builder_product_application#'.'page', $this->get_q('page',1));

	  if (count($list_data) == 0){

	    //no data selected by previous process_select_result
	    if ($this->get_q('page') != 1 &&  $this->s_param('cms_builder_product_application#'.'page') > 1){
	      $this->q_param('page', 1);
	      return $this->action_list();
	    }

      $this->message('No data.');
	  }

    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('user_permission', $this->get_user_permission());
    $this->tmpl_assign('list_control', $list_control);

    $a_search_cond = $this->s_param('cms_builder_product_application#'.'SEARCH_COND');
    $is_search = empty($a_search_cond)  ? 0: 1;

    $this->tmpl_assign('title_noun', $is_search > 0 ? 'Search Result of' : 'List of');
    $this->tmpl_assign('clear_search_link', $is_search > 0 ? html_link(' [Clear Search Result]', $this->self_url(array('action'=>'clearsearch','oid'=>$oid))) : '');
    $this->tmpl_assign('list_data', $list_data);
    $this->tmpl_assign('pagelist', $a_pagelist);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    
    return $this->load_action_tmpl('list');
  }

  /*list action row function
   *  this function will run first when processing the row
   */
  function list_row_function($dbh_r, $h_row){ 
    $oid = $h_row['oid'];
    $mid = $h_row['mid'];
    $body = $h_row['body'];

   $h_label = array(
                 'itrial_url' => array('label' => 'iTrial URL', 'function' => 'url'), 
                 'www_url2'=> array('label' => '其他URL', 'function' => 'url'),  
                 'ques_1' =>'問題1', 
                 'ques_2' =>'問題2',
                 'photo'  => array('label'=>'相片', 'function'=>'json_photo'), 
                 
                 );
  
    $member = getModel('CMS_Member');     
    $helper = getModel('CMS_Helper');  

    $member_url = '/cms/builder/member/imore.php/view/'.$mid;
    $member_url = html_link($mid, $member_url);
    $member_blacklist = $member->blacklisted($mid);
    if($member_blacklist == 1){
         $member_blacklist = '<br />已列入黑名單';
    }

    $member_application_history = html_link('過往申請紀錄', '/cms/builder/view/product_application_history.php/list/'.$mid);

    $qa = array();
    if($h_row['message_json'] !=''){
        //$qa = $helper->format_json_as_text('hash', $h_row['message_json'], $h_label);
		
		$count = 0;
		$json_decoded = json_decode($h_row['message_json'], true);
		foreach ($json_decoded as $k => $v){
			if($k == 'photo'){
				//array_push($qa, html_img("/$v", $this->param('CGI_URL').$v, '', '200x200', array('openwin'=>1))."<br />");
				list($width, $height) = getimagesize('/home/itrial/www/'.$v);
				$ratio = $width/$height;
				$width = 200;
				$height = $width*$ratio;
				array_push($qa, html_img("/$v", $this->param('CGI_URL').$v, '', "$widthx$height", array('openwin'=>1))."<br />");

			}
			if($k == 'questions'){
				foreach ($v as $answer){
				$question = db_select_one($dbh_r, "select cname from product_question where oid=? and status=1 order by priority desc, id limit $count,1",$oid);
				array_push($qa, "問題: $question<br /> 答案: $answer<br />");
				 $count++;
				}
			}
			// echo "K: $k, V: $v";
		}; 
	}
/*
    return array(
      'mid'        => $member->basic_info($mid).'<br />'.$member_url.'<br />'.$member_application_history,
*/

	$member_address = db_select_one($dbh_r, 'select address from member_condition where mid=?', $mid);
    return array(
      //'mid'        => $member->basic_info($mid).'<br /><br />'."地址: $member_address<br /><br />".$member_url.'<br />'.$member_application_history,

      'mid'        => $member->basic_info($mid).'<br /><br />'.$member->related_info('report',$mid, $oid).'<br /><br />'."地址: $member_address<br /><br />".$member_url.'<br />'.$member_application_history,

      'application_history'	=>	$member->related_info('application', $mid),
      'message_json' => 
           '申請試用原因:'.$body.'<BR>'.implode('<br />',$qa),
          
      );
  }

  function update_listing_ordering(){
  	$a_allowed_sorting_field = array('score');
  	if (count($a_allowed_sorting_field) == 0){
  		return array();
  	}
  	$sortbyfield = $this->s_param('cms_builder_product_application#'.'sortby');
    #echo $sortbyfield;
    $a_sortbyfield = explode(',', $sortbyfield);
    $h_sortbyfield = array();
    foreach ($a_sortbyfield as $fieldname_order){
    	$a_temp = explode(' ', $fieldname_order);
    	$field = $a_temp[0];
    	$order = isset($a_temp[1])?$a_temp[1]:'';
    	#echo 'F['.$field.'] or['.$fieldname_order.']';
      $h_sortbyfield[$field]= $order;
    }
    
    $list_control = array();
    $a_result = array();
    $count = 0;
  	foreach ($a_allowed_sorting_field as $field){
  	  $sort_order=$this->get_q('sort_'.$field, '');
  	  if ($sort_order == ''){
  	  	if (isset($h_sortbyfield[$field])){
  	    	#echo "{".$h_sortbyfield[$field].'}';
  	  	  $sort_order =  $h_sortbyfield[$field];
     	  } else {
     	  	$sort_order = 'none';
     	  }	
  	  }
  	  
  	  if ($sort_order == 'none' || $sort_order == ''){
        $list_control['sort_'.$field] = html_img('/cms/images/ico/up_down_arrow.gif', '?sort_'.$field.'=desc');
        #array_push ($a_result, $field.' none');
        #echo 'list_control none sort_ '.$field;
  	  } elseif ($sort_order == 'desc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/down_arrow.gif', '?sort_'.$field.'=asc');
  	  	array_push ($a_result, $field.' desc');
  	  	#echo 'list_control down sort_ '.$field;
  	  } elseif ($sort_order == 'asc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/up_arrow.gif', '?sort_'.$field.'=none');
     	  array_push ($a_result, $field.' asc');
     	  #echo 'list_control up sort_ '.$field;
      }
  	  
  	}
  	
  	$temp = implode(',',$a_result);
  	#echo $temp.']';
  	$this->s_param('cms_builder_product_application#'.'sortby', $temp);
  	return $list_control;
  }

  function listing_condition(){
    $a_where = array();

    array_push($a_where, "oid='".$this->get_param('pq','oid',0,'int')."'", 'and');

    $session_show_all_status = $this->s_param('cms_builder_product_application#'.'SETTING_SHOWALLSTATUS');
    switch($session_show_all_status){
      case 'status_all':
        break;
      case 'status_0':
        array_push($a_where, "status=0", "and");
        break;
      case 'status_2':
        array_push($a_where, "status=2", "and");
        break;
      case 'status_none': # no status field
        break;
      default:
        array_push($a_where, "status>=1", "and");
        break;
    }	

    $a_search_condition = $this->s_param('cms_builder_product_application#'.'SEARCH_COND');
    if (is_array($a_search_condition) && !empty($a_search_condition)){
      $a_where = array_merge($a_where, $a_search_condition);
    }

#    #array_push($a_where, "");#
#
#    $a_order = array();
#    $sortbyfield = $this->get_param('s','sortby', 'id');
#    $sortorder   = $this->get_param('s','sortorder', '');#
#
#    $a_sortbyfield = explode(',', $sortbyfield);
#    $a_sortorder   = explode(',', $sortorder);
#
#    foreach ($a_sortbyfield as $sortbyfield){
#      $sortorder = array_shift($a_sortorder);
#
#      array_push($a_order, "$sortbyfield $sortorder");
#   }

    $sortby = $this->s_param('cms_builder_product_application#'.'sortby');
    if ($sortby == ''){
    	$sortby = 'id';
    }

    $final_str = '';
    if (count($a_where) > 0){
      array_pop($a_where);
      $final_str = ' where '.implode(' ', $a_where);
    }
    #if (count($a_order) > 0){
    #  $final_str .= ' order by '.implode(' and ', $a_order);
    #}
    $final_str .= ' order by '.$sortby;
    
    return $final_str;
  }

  function action_edit($id=null){
    if (! $this->user_can('edit') ) return $this->trap();
    if ($id === null){
       $id = $this->get_param('pq','id',  0, 'int');
    }
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($id == 0
      || $oid == 0
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $application_status = $this->create_lookup_array($dbh_r, "application_status", 'id', "cname", 'where status=1'); 
    $cms_user = $this->create_lookup_array($dbh_r, "cms_user", 'id', "name", 'where status=1'); 
    $h_feature = array(
      
      '#ROW_FUNCTION#' => 'edit_row_function',      
      'oid'              => array('f:func',          'oid',             'html_fix_edit_text'),
      'application_status' => array('h:label',         'application_status', $application_status ,array()),
      'body'             => array('f:func',          'body',            'html_fix_edit_textarea'),
      'score'            => array('f:func',          'score',           'html_fix_edit_text'),
      'is_fb_share'      => array('ny:radio',        'is_fb_share',     ),
      'email_sent'       => array('ny:radio',        'email_sent',      ),
      'application_history' => array('f:func',          'application_history', 'html_fix_edit_text'),
      'is_approved'      => array('ny:radio',        'is_approved',     ),
      'addedby'          => array('h:label',         'addedby',         $cms_user ,array()),
      'modifiedby'       => array('h:label',         'modifiedby',      $cms_user ,array()),
      'approvedby'       => array('h:label',         'approvedby',      $cms_user ,array()),
      'status'           => array('status:radio',    'status',          ),
                       );
    
    if ( $this->user_can('approve', 1) ){
    	$h_feature['status'] = array('status:radio',    'status',          );
    } else {
    	$h_feature['status'] = array('status:label',    '',          );
    }	

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    
    $this->audit_log('edit', $id);
    
    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('edit_data', $h_row[0]);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('edit');
  }

  /*edit action row function
   *  this function will run first when processing the row
   */
  function edit_row_function($dbh_r, $h_row){    
 $mid = $h_row['mid'];

   $h_label = array(
                 'itrial_url' => array('label' => 'iTrial URL', 'function' => 'url'), 
                 'www_url2'=> array('label' => '其他URL', 'function' => 'url'),  
                 'ques_1' =>'問題1', 
                 'ques_2' =>'問題2',
                 'photo'  => array('label'=>'相片', 'function'=>'json_photo'), 
                 
                 );
  
    $member = getModel('CMS_Member');     
    $helper = getModel('CMS_Helper');  
    return array(
      'mid'        => $member->basic_info($mid),
      'message_json' => $member->related_info('report', $mid).'<BR>'. 
$helper->format_json_as_text('hash', $h_row['message_json'], $h_label)
      );
  }

  function action_view(){
    if (! $this->user_can('view') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($id == 0
      || $oid == 0
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');

    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $cms_user = $this->create_lookup_array($dbh_r, "cms_user", 'id', "name", 'where status=1'); 
    $h_feature = array(
      
      'is_fb_share'      => array('ny:label',        'is_fb_share',     ),
      'email_sent'       => array('ny:label',        'email_sent',      ),
      'addedby'          => array('h:label',         'addedby',         $cms_user ,array()),
      'modifiedby'       => array('h:label',         'modifiedby',      $cms_user ,array()),
      'approvedby'       => array('h:label',         'approvedby',      $cms_user ,array()),
      'status'           => array('status:label',    'status',          ),
                        );

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    $this->audit_log('view', $id);
    
    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('view_data', $h_row[0]);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('view');
  }

  function action_update(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($id === false
      || $oid == 0
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_w    = $this->db_connect('write');
    $original_status = db_select_one($dbh_w, 'select status from '.$this->param('table').' where id=?', $id);

    $h_feature = array(

    );
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);
    $upload_changed = 0;
    
    if ($changed > 0 || $upload_changed > 0){
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id=?", array($this->get_cms_userid(),$id)); 
      
      $this->audit_log('update', $id);
    }
    
    $new_status      = $this->get_q('status');
    if ($original_status != 0 && $new_status == 0){
      $this->on_after_del(array('oid'=>$oid), $id);
    }
   	
  if ($changed > 0  || $upload_changed > 0){
    $this->on_after_update(array('oid'=>$oid), $id);
  }  
  
    if ($this->get_q('subaction') == 'edit_after_update'){
      return $this->action_edit($id);
    }
    return  $this->cms_redirect_default_action( array('oid'=>$oid) );
  }

/*
 * $this->on_after_update(array('oid'=>$oid, 'topid'=>$topid));
 *  oid, topid may be unavailable
 *  $id: id of the record just edited
 */
function on_after_update($h_param, $id){
  // $oid = $param['oid'];

  $dbh_w = $this->db_connect();

  list( $application_status, $is_approved) = db_selectrow_array($dbh_w, 'select application_status, is_approved from '.$this->param('table').' where id=? and status=1', $id);
  if($application_status < 7 &&  $is_approved == 1){
      db_do($dbh_w, 'update '.$this->param('table').' set application_status=7 where id=?', $id);
  }else if($application_status == 7 && $is_approved == 0){
      db_do($dbh_w, 'update '.$this->param('table').' set application_status=1 where id=?', $id);
  }

}

  function action_mupdate(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    
    $h_feature = array(
    
    );
    
    //$this->mupdate_modify_feature(\%feature) if ($this->can('mupdate_modify_feature'));

    $a_changed = $this->update_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    $a_id = $this->q_param('id');
    foreach ($a_id as $id){
      $upload_changed = 0;
      
      if ($upload_changed > 0 && !in_array($id, $a_changed)){    
         array_push($a_changed, $id);
       } 

    }

    if (count($a_changed)>0){
      $changed = implode(',' , $a_changed);
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id in ($changed)", array($this->get_cms_userid()));       
      $this->audit_log('update', $changed);
    }

    $this->on_after_mupdate(array('oid'=>$oid), $a_changed);
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }
    
  /*
 * $this->on_after_mupdate(array('oid'=>$oid, 'topid'=>$topid), $a_changed);
 *  oid, topid may be unavailable
 *  $a_changed is all ID being updated
 */
function on_after_mupdate($h_param, $a_changed ){
  // $oid = $param['oid'];

  $dbh_w = $this->db_connect();

  foreach ($a_changed as $id){
	  list( $application_status, $is_approved) = db_selectrow_array($dbh_w, 'select application_status, is_approved from '.$this->param('table').' where id=? and status=1', $id);
	  if($application_status < 7 &&  $is_approved == 1){
		  db_do($dbh_w, 'update '.$this->param('table').' set application_status=7 where id=?', $id);
	  }else if($application_status == 7 && $is_approved == 0){
		  db_do($dbh_w, 'update '.$this->param('table').' set application_status=1 where id=?', $id);
	  }
	}
}  

  function action_showadd(){
    if (! $this->user_can('add') ) return $this->trap();
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($oid == 0) throw new CgiappErrorException(100,  __METHOD__.'Invalid Parameter');

    $dbh_r = $this->db_connect('read');

    $application_status = $this->create_lookup_array($dbh_r, "application_status", 'id', "cname", 'where status=1'); 
    $h_feature = array(
      
      'application_status' => array('h:label',         'application_status', $application_status ,array()),
      'is_fb_share'      => array('ny:radio',        'is_fb_share',     ),
      'email_sent'       => array('ny:radio',        'email_sent',      ),
      );
    $h_default_value = array(
      'oid' => '',
      'mid' => '',
      'application_status' => '1',
      'body' => '',
      'score' => '50',
      'is_fb_share' => '',
      'email_sent' => '',
      'application_history' => '',
      'accept_endtime' => '',
      'is_approved' => '',
      );
                 
    $showadd_data = $this->process_showadd_feature($dbh_r, $h_feature, $h_default_value);

    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('showadd_data', $showadd_data);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showadd');
  }

  function action_add(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_r = $this->db_connect();

$count = db_select_one($dbh_r, 'select count(*) from '.$this->param('table').' where mid=? and oid=?', array($mid, $oid));
	
if($count >0){
    $this->message("用戶: $mid 已曾參加此活動");
    return $this->cms_redirect_default_action(array('oid'=>$oid));
}
  
    $dbh_w    = $this->db_connect('write'); # db_connect default is readonly

    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 

    );
    $changed = $this->add_to_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0 ){
      $id = db_last_insert_id($dbh_w);
      db_do($dbh_w, "update ".$this->param('table')." set addtime=NOW(),lastmodify=NOW(),addedby=?,modifiedby=? where id=?", array($this->get_cms_userid(),$this->get_cms_userid(),$id)); 
      
    }
    $upload_changed = 0;
     
    $this->audit_log('add', $id);

  if ($changed > 0  || $upload_changed > 0){
    $this->on_after_add(array('oid'=>$oid), $id);
  }  
  
  if ($this->get_q('subaction') == 'edit_after_add'){
    return $this->action_edit($id);
  }
  
  if ($this->get_q('subaction') == 'showadd_after_add'){
	  return $this->action_showadd();
	}
  
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

/*
 * $this->on_after_add(array('oid'=>$oid, 'topid'=>$topid));
 *  oid, topid may be unavailable
 * $id: id of record just added
 */
function on_after_add($h_param, $id){
   $oid = $h_param['oid'];

   $dbh_w = $this->db_connect('write');
   
   list($mid) = db_selectrow_array($dbh_w, 'select mid from '.$this->param('table').' where id=?', $id);
   list($product_cname, $product_point) = db_selectrow_array($dbh_w, 'select name, points from product where id=? and status=1', $oid);
   
   $points = getModel('CMS_Points');
   $a_result = $points->points_record($mid, "submit_product_invite", str_replace("[產品名稱]", $product_cname, SUBMIT_PRODUCT_INVITE_LANG), $oid, $product_point);
   
   if($a_result['ret'] == 0){
		db_do($dbh_w, 'update '.$this->param('table').' set status=0 where id=?', $id);
		$this->message('Not enough point to be deducted, Cannot join this event');
		return;
	}
   db_do($dbh_w, 'update product set apply_num=apply_num+1 where id=? and status=1', $oid);
}

  function action_madd(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w       = $this->db_connect('write');
    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 
    #'addtime' => 'addtime', 'lastmodify' => 'lastmodify',
    
    );
    $changed   = $this->add_to_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if (count($a_changed) > 0){
      foreach ($a_changed as $id){
        $row_affected = $dbh_w->exec("update ".$this->param('table')." set lastmodify = NOW() where id = '$id'") ;
      }
    }
    
		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('madd', $changed_id);
	  }
	
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

  /*
   *
   */
  function action_del(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(

    '#DELETE_MODE#' => 'hidden'
   );
    $this->delete_from_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_param);
    
    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id=?", array($this->get_cms_userid(),$id)); 
    $this->audit_log('del', 'hidden-'.$id);
    $this->on_after_del(array('oid'=>$oid), $id);
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

/*
 * $this->on_after_del(array('oid'=>$oid, 'topid'=>$topid));
 *  oid, topid may be unavailable
 * $id: id of record just deleted.
 */
function on_after_del($h_param, $id){

   $oid = $h_param['oid'];

   $dbh_w = $this->db_connect('write');

   db_do($dbh_w, 'update product set apply_num=apply_num-1 where id=? and status=1', $oid);
	return;
}

  function action_mdel(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    # input check
    $a_selected   = array();
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }
    if (count($a_selected) == 0){
    	$this->message('Please select the ID for records to be deleted!');
      return $this->cms_redirect_default_action(array('oid'=>$oid));    	
    }
    # end input check
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(
      
      '#DELETE_MODE#' => 'hidden'
      );
    $a_changed = $this->delete_multiple_from_table($dbh_w, $this->param('table'),'HTTP_POST', $h_param);
    
 		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id in ($changed_id)", array($this->get_cms_userid())); 
	  }

		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('mdel', 'hidden-'.$changed_id);
	  }
	
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

  function action_help(){
  	#if (! $this->user_can('help') ) return $this->trap();
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
  	return $this->load_action_tmpl('help');
  }
/**HELP:__HELP**/

  function action_showsearch(){
    if (! $this->user_can('list') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($oid == 0) throw new CgiappErrorException(100,  __METHOD__.'Invalid Parameter');

    $dbh_r = $this->db_connect('read');
    $h_default_value = array(
      'oid'=>'',# add session support later
      'mid'=>'',# add session support later
      'application_status'=>'1',# add session support later
      'body'=>'',# add session support later
      'score'=>'50',# add session support later
      'is_fb_share'=>'',# add session support later
      'email_sent'=>'',# add session support later
      'application_history'=>'',# add session support later
      'accept_endtime'=>'',# add session support later
      'is_approved'=>'',# add session support later
      );

    $h_feature = array(
      'mid' => 'search_int',
      'is_fb_share'      => array('ny:radio',        'is_fb_share',     ),
      'email_sent'       => array('ny:radio',        'email_sent',      ),
      'is_approved'      => array('ny:radio',        'is_approved',     ),
                 );

    $showsearch_data = $this->process_showsearch_feature($dbh_r, $h_feature, $h_default_value);
    $this->tmpl_assign('showsearch_data', $showsearch_data);

    $this->tmpl_assign('oid', $oid);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showsearch');
  }

  function clearsearch(){
  	$oid = $this->get_param('pq','oid', 0, 'int');
    
    $this->search_clear('cms_builder_product_application#');
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

  function action_search(){
    if (! $this->user_can('list') ) return $this->trap();
    #<!--START:__PSAUTH-->return $this->psauth_no_access() if (not $this->psauth_can_access('search'));<!--END:__PSAUTH-->

    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $h_feature = array(
      
      );
    list ($flag, $a_condition) = $this->search_build_sql($h_feature);
    if ($flag == 1){
      return $this->errmsg('no_search_input', 2) ;
    }

    if (is_array($a_condition)  && !empty($a_condition)){
      $this->s_param('cms_builder_product_application#'.'SEARCH_COND', $a_condition);
    }

    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

/**START:COPY**/

##COPY_TYPE_FUNC##
  function action_copy(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w = $this->db_connect('write');

    $h_param = array(
    
                   );

    list($count, $new_id)=  $this->copy_row_by_key($dbh_w, $this->param('table'), 'id', $id, $h_param);
    #my ($count, $new_id) = $this->copy_row_by_key($dbh, $this->param('table'), 'id', $id, '', %feature);
    /**START:COPY_BY_FK_HAS_CHILD**/
    if ($this->q_param('subaction') == 'with_child'){
      #$this->##PS_SHARE_CHILD_MODULE_PREFIX##copy_by_parent_key($id, $new_id);
    }
    /**END:COPY_BY_FK_HAS_CHILD**/

    return  $this->action_edit($new_id);
  }

/**END:COPY**/

// Supplementary function add here

  // ajas update a field
  function ajax_update_field(){
    $id   = $this->get_q('id', 0, 'int');
    if ($id == 0) return 'invalid ID';

    ################################################
    # General update, common for all
    ################################################

    $dbh_w    = $this->db_connect('write');
    $h_feature = array();
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0){
      $row_affected = db_do($dbh_w, "update ".$this->param('table')." set lastmodify = NOW() where id =?", array($id)) ;
    }

    $dbh_r    = $this->db_connect('read');
    $field  = $this->q_param('#FIELD#');
    list ($value) = db_selectrow_array($dbh_r, "select $field from ".$this->param('table')." where id=?", array($id));
//    ### custom, change by type table
//    if ($field == 'aseip'){
//      list ($value) = db_selectrow_array($dbh, "select cname from test.dummy_type where id=?", array($value));
//    return $value;
//    }
//    #####

    return $value;

  }

/* Custom Class Function Implementation start here */

function action_user_accept_invite(){
	$dbh_w = $this->db_connect();
    $oid = $this->get_param('pq','oid', 0, 'int');
    # input check
    $a_selected   = array();
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }
    if (count($a_selected) == 0){
    	$this->message('Please select the ID for records to be updated!');
      return $this->cms_redirect_default_action(array('oid'=>$oid));    	
    }
	$report_endtime = db_select_one($dbh_w, 'select report_endtime from product where id=? and status=1', $oid);
	$accept_endtime = strtotime("+3 day");
	$accept_endtime = date("Y-m-d H:i:s",$accept_endtime);
	

   list($product_cname, $product_point) = db_selectrow_array($dbh_w, 'select name, points from product where id=? and status=1', $oid);
   $a_failed_application = array();
   $points = getModel('CMS_Points');
    foreach($a_selected as $selected_id){
		list($mid, $application_status) = db_selectrow_array($dbh_w, 'select mid,application_status from '.$this->param('table').' where id=? and status=1', $selected_id);
		
		$a_result = $points->points_record($mid, "confirm_product_invite", str_replace("[產品名稱]", $product_cname, CONFIRM_PRODUCT_INVITE_LANG), $oid, $product_point);
		
		if($a_result['ret'] == 0){
			array_push($a_failed_application, "ID: $selected_id, Member id: $mid");
		}
		
        db_do($dbh_w, 'update product_application set email_sent=1, accept_endtime=?, application_status=9, lastmodify=NOW(),modifiedby=?  where id=?', array($accept_endtime, $this->get_cms_userid(), $selected_id));
		
		$count = db_select_one($dbh_w, 'select count(*) from member_application where mid=? and product=? and status=1', array($mid, $oid));
		if($count <=0){
			db_do($dbh_w, "insert into member_application (mid, product, report_endtime, addtime, lastmodify) values (?,?,?,NOW(),NOW())", array($mid, $oid, $report_endtime)); 
		}

    }
	if(!empty($a_failed_application)){
		$this->message(implode("<br />", $a_failed_application));
	}
    return $this->cms_redirect_default_action(array('oid'=>$oid));
}

function action_add_participant(){

	$dbh_w = $this->db_connect();
    $oid = $this->get_param('pq','oid', 0, 'int');
    # input check
    $a_selected   = array();
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }
    if (count($a_selected) == 0){
    	$this->message('Please select the ID for records to be updated!');
      return $this->cms_redirect_default_action(array('oid'=>$oid));    	
    }
    # end input check

    $report_endtime = db_select_one($dbh_w, 'select report_endtime from product where id=? and status=1', $oid);

	foreach($a_selected as $selected_id){
		list($mid, $application_status) = db_selectrow_array($dbh_w, 'select mid,application_status from '.$this->param('table').' where id=? and status=1', $selected_id);
		//echo "Mid: $mid, status: $application_status";exit;
		if($application_status == 7){
			$accept_endtime = strtotime("+3 day");
			$accept_endtime = date("Y-m-d H:i:s",$accept_endtime);
			
			//echo "$accept_endtime, ".$this->get_cms_userid().", $selected_id";
			db_do($dbh_w, "update ".$this->param('table')." set email_sent=1, accept_endtime=?, lastmodify=NOW(),modifiedby=? where id=?", array($accept_endtime, $this->get_cms_userid(), $selected_id)); 			
		}else if($application_status == 9){
			$count = db_select_one($dbh_w, 'select count(*) from member_application where mid=? and product=? and status=1', array($mid, $oid));
			if($count <=0){

				db_do($dbh_w, "insert into member_application (mid, product, report_endtime, addtime, lastmodify) values (?,?,?,NOW(),NOW())", array($mid, $oid, $report_endtime)); 
			}
		}
	}

	return $this->cms_redirect_default_action(array('oid'=>$oid));
}

function action_update_accept_period(){

	$dbh_w = $this->db_connect();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    # input check
    $a_selected   = array();
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }
    if (count($a_selected) == 0){
    	$this->message('Please select the ID for records to be updated!');
      return $this->cms_redirect_default_action(array('oid'=>$oid));    	
    }
    # end input check
    
	//print_r($a_selected);exit;
    $accept_endtime = strtotime("+3 day");
	
	$accept_endtime = date("Y-m-d H:i:s",$accept_endtime);

	foreach($a_selected as $selected_id){
		db_do($dbh_w, "update ".$this->param('table')." set accept_endtime=?, lastmodify=NOW(),modifiedby=? where id=?", array($accept_endtime, $this->get_cms_userid(), $selected_id)); 
	}	
	return $this->cms_redirect_default_action(array('oid'=>$oid));
}
/*
function action_send_mail(){

	$id = $this->get_param('pq', 'id');
	$oid = $this->get_param('pq', 'oid');
	$dbh_w = $this->db_connect('write');

   list($success, $msg) = $this->send_mail_impl($dbh_w, $id);
  
   if($success){
		$this->message($msg);
   }else{
		$this->message($msg);
   }
   return $this->cms_redirect_default_action(array('oid'=>$oid));
}
*/
function action_send_mail(){

	$id = $this->get_param('pq', 'id');
	$oid = $this->get_param('pq', 'oid');
	$dbh_w = $this->db_connect('write');
	
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
	
	$a_selected   = array();
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }

	$select_total = count($a_selected);
    if ($select_total == 0){
    	$this->message('Please select the ID for records to be deleted!');
      return $this->cms_redirect_default_action(array('oid'=>$oid));    	
    }

	$a_failed_id = array();
	foreach ($a_selected as $selected_id){
		list($success, $msg) = $this->send_mail_impl($dbh_w, $selected_id);
		if($success == 0){
			array_push($a_failed_id, $selected_id);
		}
	}
	
	if(count($a_failed_id) == 0){
		$this->message('成功發送');
	}else{
		$this->message("發送錯誤: ");
		$this->message('ID:'.implode(',', $a_failed_id));
	}

   return $this->cms_redirect_default_action(array('oid'=>$oid));
}
function send_mail_impl($dbh_w, $id){
/*
   $email_sent = db_select_one($dbh_w, 'select email_sent from '.$this->param('table').' where id=? and status=1', $id);

   if($email_sent == 1){
	return array(0, 'Email 已曾發送');
   }
*/
   $success = file_get_contents($this->param('CGI_URL').'/product.php?action=emailApplication&aid='.$id.'&key='.md5($id."imoreHK"));
   
   if($success){
	db_do($dbh_w, 'update '.$this->param('table').'  set email_sent =1 where id=? ', $id);
	return array(1, '成功發送');
   }
	return array(0, '發送錯誤');
}

function update_score(){
	$oid = $this->get_param('pq', 'oid');

  $dbh_r = $this->db_connect('read');
  $dbh_w = $this->db_connect('write');
  
  $member = getModel('CMS_Member');
  
  $ids = db_selectcol_array($dbh_r, 'select id from '.$this->param('table').' where oid=? and status=1', $oid);
  foreach ($ids as $id){
    $score = 50;
  	$mid = db_select_one($dbh_r, 'select mid from '.$this->param('table').'  where id=?', $id);
  	
  	if ($member->blacklisted($mid)){
  	  $score -= 50;
    }
    
    db_do($dbh_w, 'update '.$this->param('table').' set score=? where id=?', array($score, $id));
  }
  
   return $this->cms_redirect_default_action(array('oid'=>$oid));
}

}//end class

$webapp = new cms_builder_product_application(
   array('PARAMS' => array_merge($site_global_config, $local_config))
         );
$webapp->run();

/* Custom Helper Function Implementation start here */

?>
